function varargout = TLDflipflopDlg(action,varargin)

% TL_DFLIPFLOP_DLG manages the user interface for TargetLink D-Flip-Flop block
%
% SYNTAX dlgInfo = TLDflipflopDlg('GetDlgInfo');
%   gets dialog info of TargetLink D-Flip-Flop block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLDflipflopDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLDflipflopDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLDflipflopDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLDflipflopDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLDflipflopDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLDflipflopDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.11 $
% $Date: 2011/03/17 12:04:49MEZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'D Flip-Flop';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = { 
            'Output';
            'Logging & Autoscaling';
            'Documentation' };
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Output'
                [sheetDims, ctrlPos] = FcnCalcOutputCtrlPositions(commonGeom);

            case 'Logging & Autoscaling'
                [sheetDims, ctrlPos] = FcnCalcLoggingCtrlPositions(commonGeom, sheetDims);

            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims, ctrlPos] = TLManageDocCtrls( ...
                    'ctrlpos', commonGeom, sheetDims, bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                dlgdata = FcnCreateOutputControls(pageNum, dlgfig, dlgdata);

            case 'Logging & Autoscaling'
                dlgdata = FcnCreateLoggingCtrls(pageNum, dlgfig, dlgdata);

            case 'Documentation'
                dlgdata =  TLManageDocCtrls('create', pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                [dlgdata, bModified] = ...
                    FcnManageOutputControls(pageNum, dlgfig, dlgdata, pageAction);

            case 'Logging & Autoscaling'
                [dlgdata, bModified] = FcnManageLoggingCtrls(pageNum, dlgdata, pageAction);

            case 'Documentation'
                [dlgdata,bModified] = ...
                    TLManageDocCtrls('callback',pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};

        pageName  = dlgdata.pageNames{pageNum};

        switch pageName
            case 'Output'
                dlgdata = FcnUpdateOutputControls(dlgdata, dlgfig, pageNum);

            case 'Logging & Autoscaling'
                dlgdata = FcnUpdateLoggingCtrls(pageNum, dlgfig, dlgdata);

            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        blockVar{1} = 'output';
        blockVar{2} = 'noutput';
        idx = get(dlgdata.pageData{1}.children.selectPopup,'Value');
        tl_create_links_to_model('ShowComputation',dlgdata.model, blockVar{idx});

    otherwise
        error('Invalid callback');

end % switch(action)


% -------------------------------------------------------------------------
% FcnCalcOutputCtrlPositions calculates positions for all controls on output page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcOutputCtrlPositions(commonGeom)

excludedCtrls = { };
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = {'Select:', 'text'};
selectLabelSize = ds_get_uicontrol_sizes(commonGeom, strings_and_styles);

%-----------------------------------------------------------
% enlarge groupboxes
%-----------------------------------------------------------
% calculate extra space needed for select popup
dy = commonGeom.editHeight + rowDelta;

% enlarge tlcgGroupbox
ctrlPos.tlcgoptGroupbox(4) = ctrlPos.tlcgoptGroupbox(4) + dy;

%-----------------------------------------------------------
% supplement tlcgGroupbox
%-----------------------------------------------------------
cy = ctrlPos.descLabel(2) + commonGeom.editHeight + rowDelta;

% select label
cx = col(1);
ctrlPos.selectLabel = [cx cy selectLabelSize];

% select popup
cx = col(2);
ctrlPos.selectPopup = [cx cy ctrlPos.lsbEdit(3:4)];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) ...
    + dy;


%-----------------------------------------------------------------------------------------
% FcnCreateOutputControls creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateOutputControls(pageNum,dlgfig,dlgdata)

% create all controls
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
Children = dlgdata.pageData{pageNum}.children;

% variable select controls
Children.selectLabel = uicontrol( ...
    'Parent',             Children.tlcgoptGroupbox, ...
    'String',             'Select:', ...
    'Style',              'text', ...
    'Position',           ctrlPos.selectLabel);

Children.selectPopup = uicontrol( ...
    'Parent',             Children.tlcgoptGroupbox, ...
    'Style',              'popupmenu', ...
    'String',             {'Q'; '!Q'}, ...
    'BackgroundColor',    'w', ...
    'Position',           ctrlPos.selectPopup);

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageOutputControls manages control actions of output page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageOutputControls(pageNum,dlgfig,dlgdata,pageAction)

Children  = dlgdata.pageData{pageNum}.children;
fieldIdx  = get(Children.selectPopup, 'Value');
vars = {'output', 'noutput'};
field = vars{fieldIdx};

switch pageAction
    case 'selectPopup'
        bModified = 1;

    otherwise
        [dlgdata, bModified1] = TLManageVariableCtrls( ...
            'manage', pageNum, dlgfig, dlgdata, pageAction, field);
        [dlgdata, bModified2] = TLManageScalingCtrls( ...
            'manage', pageNum, dlgfig, dlgdata, pageAction, field);
        
        bModified = bModified1 || bModified2;
end


%--------------------------------------------------------------------------
% FcnUpdateOutputControls updates the controls of the output tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateOutputControls(dlgdata, dlgfig, pageNum)

Children = dlgdata.pageData{pageNum}.children;
fieldIdx = get(Children.selectPopup, 'Value');
vars = {'output', 'noutput'};
field = vars{fieldIdx};

% default control status
selectPopupCtrlStatus = struct('enable', 'on', ...
    'string', {{'Q'; '!Q'}}, 'value', 1);
selectPopupCtrlStatus.value = fieldIdx;

dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, field);
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, field, []);

ctrlsList = {'selectPopup'};
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set standard controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

% set non-standard controls
TLSetCtrlsStatus(dlgfig, Children, ctrlsList);


%-----------------------------------------------------------------------------------------
% FcnCalcLoggingCtrlPositions calculates positions for all controls on logging page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%   sheetDims       dimension of sheet
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcLoggingCtrlPositions(commonGeom, sheetDims)

excludedCtrls = {'keepParameter'};
[sheetDims, ctrlPos] = ...
    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

[selectLabelSize, selectPopupSize] = ds_get_uicontrol_sizes(commonGeom, ...
    {'Select:',  'text'; ...
    'whatever', 'popupmenu'});

widths = selectPopupSize(1);
[col,colWidth,colDelta,rowDelta] = ds_get_gui_columns(widths,commonGeom);

% enlarge logplotGroupbox
ctrlPos.logplotGroupbox(4) = ...
    ctrlPos.logplotGroupbox(4) + commonGeom.editHeight + rowDelta;

cy = ctrlPos.logLabel(2) + commonGeom.editHeight + rowDelta;

% selection label
cx = ctrlPos.logLabel(1);
ctrlPos.selectLabel = [cx cy selectLabelSize];

% selection popup
cx = ctrlPos.logPopup(1);
ctrlPos.selectPopup = [cx cy selectPopupSize];


%-----------------------------------------------------------------------------------------
% FcnCreateLoggingCtrls creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateLoggingCtrls(pageNum, dlgfig, dlgdata)

dlgdata = TLManageLoggingCtrls('create',pageNum,dlgfig,dlgdata);

Children = dlgdata.pageData{pageNum}.children;
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;

% selection popup
Children.selectLabel = uicontrol( ...
    'Parent',             Children.logplotGroupbox, ...
    'Style',              'text', ...
    'String',             'Select:', ...
    'Position',           ctrlPos.selectLabel);

Children.selectPopup = uicontrol( ...
    'Parent',             Children.logplotGroupbox, ...
    'Style',              'Popupmenu', ...
    'BackgroundColor',    'w', ...
    'String',             {'Q'; '!Q'}, ...
    'Value',              1, ...
    'Position',           ctrlPos.selectPopup);

dlgdata.pageData{pageNum}.children = Children;

% set special values that are not overwritten by global function
dlgdata.extdata.logdata.bLimHroom = 1;
dlgdata.extdata.logdata.maxHroom  = Inf;


%-----------------------------------------------------------------------------------------
% FcnManageLoggingCtrls manage control actions of table page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageLoggingCtrls(pageNum, dlgdata, action)

Children = dlgdata.pageData{pageNum}.children;

switch action
    case 'selectPopup'
        bModified = 1;

    otherwise
        selectIdx = get(Children.selectPopup, 'value');
        logVars = {'logdata', 'nlogdata'};
        [dlgdata, bModified] = ...
            TLManageLoggingCtrls('manage', pageNum, dlgdata, action, logVars{selectIdx});
end


%--------------------------------------------------------------------------
% FcnUpdateLoggingCtrls updates the controls of the documentation tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateLoggingCtrls(pageNum, dlgfig, dlgdata)

Children = dlgdata.pageData{pageNum}.children;

selectIdx = get(Children.selectPopup, 'value');
vars = {'output', 'noutput'};
logVars = {'logdata', 'nlogdata'};
dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,logVars{selectIdx},vars{selectIdx});
TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);
